
import Utils from "./utils.js"
import Watcher from "./watcher.js"

function Compile(el, vm) {
  this.vm = vm
  this.$el = this.isNode(el) ? el : document.querySelector(el)
  const f = this.createFrag()
  console.dir(f)
  this.compileFrag(f)
  vm.$option.beforeMount()
  this.$el.appendChild(f)
  vm.$el = this.$el
  vm.$option.mounted()
}

Compile.prototype.createFrag = function () {
  let frag = document.createDocumentFragment()
  let firstNode
  while (firstNode = this.$el.firstChild) {
    frag.appendChild(firstNode)
  }
  return frag
}

Compile.prototype.compileFrag = function (frag) {
  const childs = frag.childNodes
  if (childs.length > 0) {
    childs.forEach(child => {
      if (this.isNode(child)) {
        if (child.attributes.length > 0) {
          const attrs = Array.from(child.attributes)
          attrs.forEach(attr => {
            const { name, value } = attr
            if (this.isDirect(name)) {
              // console.log(name + '----' + value)
              // v-bind v-if v-on:click v-text
              const [,director] = name.split('v-')
              // console.log(director)
              const [directorName, eventName] = director.split(':')
              // console.log(directorName)
              // console.log(eventName)
              Utils[directorName](child, this.vm, value, eventName)
            } else if (this.isEvent(name)) {
              const [directorName, eventName] = name.split('@')
              // console.log('event-----')
              // console.log(eventName)
              Utils['on'](child,this.vm, value, eventName)
            }
          })
        }
        // {{msg}}
        if (this.isLineInsert(child.innerHTML)) {
          const innerH = child.innerHTML
          const val = innerH.match(/\{\{(.+)\}\}/)[1].trim()
          Utils['text'](child, this.vm, val)
        }
        if (child.childNodes.length > 0) {
          this.compileFrag(child)
        }
      }
    })
  }
}
Compile.prototype.isLineInsert = function (str) {
  return /^\{\{(.+)\}\}$/.test(str)
}
Compile.prototype.isDirect = function (str) {
  return str.startsWith('v-')
}
Compile.prototype.isEvent = function (str) {
  return str.startsWith('@')
}

Compile.prototype.isNode = function (el) {
  return el.nodeType === 1
}

export default Compile